package core {
	import jazztures.Jazztures;
	import jazztures.events.SkeletonEvent;
	import jazztures.events.UserEvent;
	import jazztures.objects.Skeleton;

	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.utils.Dictionary;
	
	
	public class SkeletonTest extends Sprite
	{		
		private var kinect:Jazztures;
		private var users:Dictionary;
		
		public function SkeletonTest()
		{
			super();
			
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			addEventListener(Event.ADDED_TO_STAGE, addedToStageListener);
		}
		
		private function addedToStageListener(evt:Event):void{
			removeEventListener(Event.ADDED_TO_STAGE, addedToStageListener);

			kinect = new Jazztures("127.0.0.1", 666);
			kinect.connect();
			
			users = new Dictionary();
			
			kinect.addEventListener(UserEvent.ADD_USER, addUser);
			kinect.addEventListener(UserEvent.REMOVE_USER, removeUser);
			
			kinect.addEventListener(SkeletonEvent.ADD_SKELETON, addSkeleton);
			kinect.addEventListener(SkeletonEvent.UPDATE_SKELETON, refreshSkeleton);
			kinect.addEventListener(SkeletonEvent.REMOVE_SKELETON, removeSkeleton);
			
			build();
		}
		
		protected function build():void{
			throw new Error("missing override build");
		}
			
		private function refreshSkeleton(evt:SkeletonEvent):void{
			if(!users[evt.id]) addUser(new UserEvent(UserEvent.ADD_USER, evt.id));
			if(!users[evt.id].skeleton) addSkeleton(evt);
			updateSkeleton(evt.skeleton, users[evt.id].skeleton);
		}
				
		private function addSkeleton(evt:SkeletonEvent):void{
			if(!users[evt.id]) addUser(new UserEvent(UserEvent.ADD_USER, evt.id));
			trace("addSkeleton", evt.id);
			users[evt.id].skeleton = createSkeleton();
		}
		
		private function removeSkeleton(id:int):void{
			if(!users[id]) return;
			trace("removeSkeleton", id);
			destroySkeleton(users[id].skeleton);
			users[id].skeleton = null;
		}
		
		private function addUser(evt:UserEvent):void{
			trace('addUser', evt.id);
			users[evt.id] = new User(evt.id);
		}
		
		private function removeUser(evt:UserEvent):void{
			trace('removeUser', evt.id);
			if(! users[evt.id]) return;
			if(users[evt.id].skeleton) removeSkeleton(evt.id);
			users[evt.id] = null;
		}
		
		protected function updateSkeleton(skeleton:Skeleton, skeleton3D:Object):void{
			throw new Error("missing override updateSkeleton");
		}
		
		protected function createSkeleton():Object{
			throw new Error("missing override createSkeleton");
		}
		
		protected function destroySkeleton(skeleton:Object):void{
			throw new Error("missing override destroySkeleton");
		}
	}
}